<?php
include_once 'core.php';
include_once 'fun.php';

define('游客', 0);
define('会员', 1);
define('技师', 2);
define('商家', 3);
define('管理员', 4);

define('c', [
  'get' => 0,
  'up' => 1,
  'add' => 2,
  'del' => 3,
  'reg' => 1001, // 注册
  'getToken' => 1002, // 获取token
  'getTokenByWxID' => 1003, // 使用token
  'getMenu' => 1004,
  'getGlobal4' => 1005, // 获取cars,itemType,notice,promise

  'getIndex' => 2001, // 获取主页数据

  'openssl_get_cipher_methods' => 999999,
  'end' => -1
]);
define('noPrem', [
  'msg' => '当前token无权限'
]);


function getSMS($tel, $timeout = 600, $codeLen = 6)
{
  return AddData(['table' => 'sms', 'tel' => $tel, 'code' => randomString($codeLen, true), 'state' => 0, 'timeout' => $timeout]);
}
function useSMS($code)
{
  $cmd = ['table' => 'sms', 'code' => $code, 'state' => 0, 'other' => ' and createTime+timeout>CURRENT_TIMESTAMP'];
  $ret = GetData($cmd);
  if ($ret) {
    UpData(['table' => 'sms', 'id' => $ret[0]['id'], 'state' => 1, 'useTime' => 'CURRENT_TIMESTAMP']);
  }
  return $ret;
}
$fun = [];

$fun[c['get']] = function ($cmd, $token = false) {
  if (!isset($cmd['table'])) return ['msg' => 'table 缺失', 'data' => $cmd];
  else $cmd['table'] = strtolower($cmd['table']);
  $ret = $token ? $token : useToken($cmd);
  unset($cmd['token']);
  if (strIn($cmd['table'], [',', ' ', '.']) && !$ret && $ret['type'] != 管理员) return noPrem;
  $show = '*';
  if ($cmd['show']) {
    $show = $cmd['show'];
    unset($cmd['show']);
  }
  if (isset($cmd['sum']) && $cmd['sum']) {
    unset($cmd['sum']);
    // return $cmd;
    $ret = GetData($cmd, 'count(*)');
    // return $ret;
    if ($ret && isset($ret[0]['count(*)'])) $ret = ['result' => ['sum' => $ret[0]['count(*)']]];
    else $ret = ['msg' => '当前条件下无数据', 'data' => $cmd];
    return $ret;
  }
  if ($ret['type'] == 会员 && strcasecmp($cmd['table'], 'itemType')) $cmd['state'] = '>0';
  if ($cmd['table'] == 'users') { // 用户列表
    if ($ret) {
      switch ($ret['type']) {
        case 会员:
          if (!isset($cmd['id'])) $cmd['id'] = $ret['id'];
          elseif ($cmd['id'] != $ret['id']) $show = 'id,display';
          break;
        case 技师:
          if ($cmd['id'] != $ret['id']) $show = 'id,display,recv';
          break;
        case 商家:
          if ($cmd['id'] != $ret['id']) $show = 'id,display,recv,type,itemType';
          break;
        case 管理员:
          # code...
          break;
        default:
          return ['msg' => 'token数据错误', 'data' => $token];
      }
    } else {
      $show = 'id,display';
    }
    $tmp = $ret['type'] != 管理员;
    $ret = GetData($cmd, $show);
    foreach ($ret as $key => $value) {
      if (isset($value['password']) && $tmp) unset($value['password']);
      if (isset($value['display'])) $value['display'] = json_decode($value['display']);
      if (isset($value['recv'])) $value['recv'] = json_decode($value['recv']);
      $ret[$key] = $value;
    }
    $ret = ['result' => $ret];
  } elseif (!(stripos($cmd['table'], 'orders') === false)) { // 订单
    if ($ret) {
      if ($ret['type'] == 会员) $cmd['buyID'] = $ret['id'];
      elseif ($ret['type'] != 管理员) {
        if ($cmd['sellID'] != $ret['id'] && $cmd['buyID'] != $ret['id']) return noPrem;
      }
      // return $cmd;
      $ret = GetData($cmd, $show);
      // return $ret;
      if (is_array($ret)) {
        $a = false;
        $b = false;
        if ($ret && isset($ret[0]['money'])) $a = true;
        if ($ret && isset($ret[0]['itemInfo'])) $b = true;
        foreach ($ret as $key => $value) {
          if ($a) $ret[$key]['money'] = json_decode($value['money'], true);
          if ($b) $ret[$key]['itemInfo'] = json_decode($value['itemInfo'], true);
        }
        $ret = ['result' => $ret];
      } else {
        $ret = ['msg' => '当前查询数据为空go', 'data' => $cmd];
      }
    } else {
      $ret = noPrem;
    }
  } elseif (!strcasecmp($cmd['table'], 'items')) { // 商品项目
    $cmd['table'] = 'items';
    if ($cmd['itemType'] == 11) {
      $cmd['flea'] = 1;
      unset($cmd['itemType']);
    }
    $ret = GetData($cmd, $show);
    if ($ret && isset($ret[0]['imgs'])) {
      foreach ($ret as $key => $value) {
        if ($value['imgs']) $ret[$key]['imgs'] = json_decode($value['imgs'], true);
      }
    }
    $ret = ['result' => $ret];
  } else $ret = ['result' => GetData($cmd, $show)];
  return $ret;
};

$fun[c['up']] = function ($cmd) {
  if (
    !isset($cmd['token']) ||
    !isset($cmd['table']) ||
    strIn($cmd['table'], [',', ' ', '.'])
  )
    return ['msg' => '必要属性 token,table缺失或table含有非法字符', 'data' => $cmd];
  if (!is_array($cmd['where'])) $cmd['where'] = [];
  // $cmd['where']['table'] = $cmd['table'];
  if (!$cmd['where']['id'] && $cmd['id']) {
    $cmd['where']['id'] = $cmd['id'];
    unset($cmd['id']);
  }
  // return $cmd;
  $no = ['msg' => '当前条件下无数据', 'data' => $cmd['where']];
  $ret = useToken($cmd);
  $token = false;
  $time = time();
  if ($ret) {
    if (!strcasecmp($cmd['table'], 'users')) { // 用户名
      $token = $ret;
      $tmp = [
        'table' => 'users',
        'changeTime' => $time,
        'where' => $cmd['where']
      ];
      $ask = 0;
      if ($cmd['password']) $tmp['password'] = $cmd['password'];
      if ($cmd['name']) $tmp['name'] = $cmd['name'];
      if ($cmd['uID']) $tmp['uID'] = (int) $cmd['uID'];
      if ($cmd['uID'] || $cmd['name']) $ask += 4;
      if ($cmd['tel']) {
        $tmp['tel'] = $cmd['tel'];
        $ask += 2;
      }
      if ($cmd['display']) $tmp['display'] = json_encode($cmd['display'], JSON_UNESCAPED_UNICODE);
      if ($cmd['recv']) $tmp['recv'] = json_encode($cmd['recv'], JSON_UNESCAPED_UNICODE);
      if ($cmd['state']) $tmp['state'] = $ret['type'] == 管理员 ? (int) $cmd['state'] : 1;
      if ($cmd['type']) $tmp['type'] = $ret['type'] == 管理员 ? (int) $cmd['type'] : 会员;
      if ($cmd['itemTypeCid']) $tmp['itemTypeCid'] =  $ret['type'] == 管理员 ? $cmd['itemTypeCid'] : 0;
      if ($cmd['other']) $tmp['other'] = $cmd['other'];
      if ($cmd['ask']) $tmp['ask'] = $ask;
      if ($ret['type'] != 管理员) $tmp['where']['id'] = $ret['id'];
      $cmd = $tmp;
    } elseif (!strcasecmp($cmd['table'], 'items')) { // 商品
      $itemType = GetData([
        'table' => 'itemType',
        'id' => $cmd['itemType'],
        'cid' => $ret['itemTypeCid'] . "&cid"
      ], '*', true);
      if ($itemType) {
        $tmp = [
          'table' => 'items',
          'changeTime' => $time,
          'cuid' => $ret['type'] == 管理员 && $cmd['sellID'] ? (int) $cmd['sellID'] : $ret['id'],
          'where' => $cmd['where']
        ];
        if ($ret['type'] != 管理员) {
          $tmp['where']['sellID'] = $ret['id'];
        }
        // return $cmd['name'];
        if ($cmd['sellID']) $tmp['sellID'] = $ret['type'] == 管理员 ? (int) $cmd['sellID'] : $ret['id'];
        if ($cmd['name']) $tmp['name'] = $cmd['name'];
        if ($cmd['trip']) $tmp['trip'] = $cmd['trip'];
        if ($cmd['citys']) $tmp['citys'] = $cmd['citys'];
        if ($cmd['notice']) $tmp['notice'] = (int) $cmd['notice'];
        if ($cmd['promise']) $tmp['promise'] = (int) $cmd['promise'];
        if ($cmd['price']) $tmp['price'] = (int) $cmd['price'];
        if ($cmd['unit']) $tmp['unit'] = $cmd['unit'];
        if ($cmd['beginTime']) $tmp['beginTime'] = (int) $cmd['beginTime'];
        if ($cmd['endTime']) $tmp['endTime'] = (int) $cmd['endTime'];
        if ($cmd['cars']) $tmp['cars'] = json_encode($cmd['cars'], JSON_UNESCAPED_UNICODE);
        if ($cmd['power']) $tmp['power'] = (int) $cmd['power'];
        if ($cmd['pageView']) $tmp['pageView'] = (int) $cmd['pageView'];
        if ($cmd['imgs']) $tmp['imgs'] = json_encode($cmd['imgs'], JSON_UNESCAPED_UNICODE);
        if ($cmd['info']) $tmp['info'] = $cmd['info'];
        if ($cmd['other']) $tmp['other'] = json_encode($cmd['other'], JSON_UNESCAPED_UNICODE);
        if ($cmd['sum']) $tmp['max'] = (int) $cmd['max'];
        $tmp['itemType'] = $itemType['id'];
        $cmd = $tmp;
        // return $cmd;
      } else return noPrem;
    } elseif (!strcasecmp($cmd['table'], 'orders')) { // 交易记录
      reset:
      // 开始判断
      switch ($ret['type']) {
        case 会员:
          $cmd['where']['buyID'] = $ret['id'];
          $cmd2 = [
            'table' => 'orders',
            'changeTime' => $time,
            'where' => $cmd['where']
          ];
          $tmp = GetData($cmd['where'], 'state,itemID,sellID,buyID,sum,money', true); // 订单
          if ($tmp) {
            $item = GetData(['table' => 'items', 'id' => $tmp['itemID']], '*', true);
            if (!$item) $item = json_decode($tmp['itemInfo'], true);
            if (!$cmd['sum']) $cmd['sum'] = $tmp['sum'];
            if ($tmp['state'] < 2 && $cmd['state'] < 2) { // 未支付
              if ($cmd['sum'] != $tmp['sum'] || isset($cmd['itemID'])) {
                if ($cmd['itemID']) $item = GetData(['table' => 'items', 'id' => $cmd['itemID']], '*', true);
                $cmd2['sum'] = $cmd['sum'];
                $cmd2['itemID'] = $cmd['itemID'];
              }
              $cmd2['money'] = json_decode($tmp['money'], true);
              $cmd2['money']['sum']['CNY'] = $item['CNY'] * $cmd['sum'];
              $cmd2['money']['sum']['point'] = $item['point'] * $cmd['sum'];
              $cmd2['money'] = json_encode($cmd2['money']);

              if ($cmd['state'] == 0 || $cmd['state'] == 1) $cmd2['state'] = $cmd['state']; //可设置关闭或开启
            } elseif ($tmp['state'] == 2 || $tmp['state'] == 3) { // 已支付。待配送 待收货
              if ($cmd['state'] == 4 || $cmd['state'] == 6) $cmd2['state'] =  $cmd['state']; // 可设置确认收货(待评价)/提出退款
            } elseif ($tmp['state'] == 4) { //等待评价
              if ($cmd['state'] == 5 || is_array($cmd['itemEval'])) {
                $cmd['state'] = 5;
                AddData([
                  'createTime' => $time,
                  'changeTime' => $time,
                  'cuid' => $ret['id'],
                  'user' => $ret['id'],
                  'name' => $cmd['itemEval']['name'],
                  'info' => $cmd['itemEval']['info'],
                  'score' => (int) $cmd['itemEval']['score'],
                  'itemID' => $item['id']
                ]);
              }
            } elseif ($tmp['state'] > 5 && $tmp['state'] < 10 && $cmd['state'] == 4) { // 可随时更改状态为确认收货
              $cmd['state'] = 4;
            } else {
              return ['msg' => '当前订单状态不允许修改', 'data' => $tmp];
            }
            $cmd = $cmd2;
            break;
          }
          return $no;
        case 技师:
          $cmd['where']['sellID'] = $ret['id'];
          $tmp = GetData($cmd['where'], '*', true);
          if ($tmp) {
            if ($tmp['state'] == 2 && $cmd['state'] == 3) $cmd2['state'] = 3;
            elseif ($tmp['state'] == 6) {
              if ($cmd['state'] == 7 || $cmd['state'] == 8) $cmd2['state'] = $cmd['state'];
            } else return ['msg' => '当前订单状态不允许修改', 'data' => $tmp];
          } else return $no;
          $cmd = ['table' => 'transactionLog', 'state' => 3, 'where' => $cmd['where']];
          break;
        case 商家:
          $tmp = GetData($cmd['where'], 'sellID,buyID', true);
          if ($tmp) { // 走技师流程
            if ($tmp['sellID'] == $ret['id']) $ret['type'] = 技师;
            elseif ($tmp['buyID'] == $ret['id']) $ret['type'] = 会员;
            else return noPrem;
            goto reset;
          }
          return noPrem;
        case 管理员:
          # code...
          break;

        default:
          return ['msg' => 'token非法', 'data' => $cmd];
          break;
      }
    } elseif (strcasecmp($cmd['table'], 'itemEval') == 0) { // 评价
      $cmd['where']['user'] = $ret['id'];
      $tmp = GetData($cmd['where'], 'id,createTime');
      if (!$tmp) return $no;
      foreach ($tmp as $value) {
        $t = (int) $value['createTime'] ? $value['createTime'] : strtotime($value['createTime']);
        $t += 7 * 24 * 60 * 60;
        if ($t < time()) return ['msg' => '只允许修改7天内的评价', 'data' => $value];
      }
      $cmd2 = ['table' => 'itemEval', 'cuid' => $ret['id'], 'where' => $cmd['where']];
      if ($cmd['name']) $cmd2['name'] = $cmd['name'];
      if ($cmd['info']) $cmd2['info'] = $cmd['info'];
      if ($cmd['score']) $cmd2['score'] = (int) $cmd['score'];
      $cmd = $cmd2;
    } elseif ($ret['type'] != 管理员) {
      return noPrem;
    }
    // return $token;
    $ret = UpData($cmd);
    // return $ret;
    if ($ret && $cmd['table'] == 'users' && $token['type'] != 管理员) {
      $cmd['username'] = $token['username'];
      $ret = getToken($cmd);
    }

    if ($ret) $ret = ['result' => $ret];
    else $ret = ['msg' => 'val参数错误', 'data' => $cmd];
  } else $ret = ['msg' => 'token失效', 'data' => $cmd];
  return $ret;
};

$fun[c['add']] = function ($cmd) {
  $ret = useToken($cmd);
  // return $ret;
  if (!strcasecmp($cmd['table'], 'users')) { // 用户
    $t = GetData(['table' => 'users', 'username' => $cmd['username']], 'id');
    if ($t) return ['msg' => '用户名已存在', 'data' => $cmd];
    $t = GetData(['table' => 'users', 'openID' => $cmd['openID']], 'id');
    if ($t) return ['msg' => 'openID已存在', 'data' => $cmd];

    $t = time();
    $cmd = [
      'table' => 'users',
      'createTime' => $t,
      'changeTime' => $t,
      'useTime' => $t,
      'username' => $cmd['username'],
      'password' => $cmd['password'],
      'type' => $ret['type'] == 管理员 && $cmd['type'] ? (int) $cmd['type'] : 会员,
      'state' => $ret['type'] == 管理员 && $cmd['state'] ? (int) $cmd['state'] : 1,
      'money' => $ret['type'] == 管理员 && $cmd['money'] ? (int) $cmd['money'] : 0,
      'display' => json_encode($cmd['display']),
      'name' => $cmd['name'],
      'uid' => $cmd['uid'],
      'tel' => $cmd['tel'],
      'recv' => json_encode($cmd['recv']),
      'itemTypeCid' => $ret['type'] == 管理员 && $cmd['itemTypeCid'] ? (int) $cmd['itemTypeCid'] : 0,
      'other' => $cmd['other'],
      'ask' => (int) $cmd['ask']
    ];
    $ret = AddData($cmd);
    $ret = ['result' => ['token' => getToken($cmd)], 'info' => $ret];
  } elseif ($ret) {
    $t = time();
    if (!strcasecmp($cmd['table'], 'items')) { // 商品项目
      $itemType = GetData([
        'table' => 'itemType',
        'id' => $cmd['itemType'],
        'cid' => $ret['itemTypeCid'] . "&cid"
      ], 'id', true);
      if ($itemType) {
        $cmd = [
          'table' => 'items',
          'createTime' => $t,
          'changeTime' => $t,
          'useTime' => 0,
          'cuid' => $ret['id'],
          'name' => $cmd['name'],
          'trip' => $cmd['trip'],
          'citys' => $cmd['citys'],
          'notice' => (int) $cmd['notice'],
          'promise' => (int) $cmd['promise'],
          'price' => (int) $cmd['price'],
          'unit' => $cmd['unit'],
          'beginTime' => (int) $cmd['beginTime'],
          'endTime' => (int) $cmd['endTime'],
          'cars' => json_encode($cmd['cars'], JSON_UNESCAPED_UNICODE),
          'power' => $ret['type'] == 管理员 ? (int) $cmd['endTime'] : 0,
          'pageView' => 0,
          'imgs' => json_encode($cmd['imgs'], JSON_UNESCAPED_UNICODE),
          'info' => $cmd['info'],
          'sellID' => $ret['type'] == 管理员 && $cmd['sellID'] ? (int) $cmd['sellID'] : $ret['id'],
          'itemType' => $itemType['id'],
          'max' => (int) $cmd['sum'],
        ];
      } else return noPrem;
    } elseif (!strcasecmp($cmd['table'], 'orders')) { // 订单系统
      $tmp = [];
      foreach ($cmd['items'] as $value) {
        $item = GetData(['table' => 'items', 'id' => $value['id']], '*', true);
        if ($item) {
          $tmp[] = [
            'table' => 'orders',
            'createTime' => $t,
            'changeTime' => $t,
            'cuid' => $ret['id'],
            'state' => $ret['id'] == 管理员 && $value['state'] ? $value['state'] : 1,
            'itemID' => $item['id'],
            'sellID' => $item['sellID'],
            'buyID' => $ret['id'] == 管理员 && $value['buyID'] ? $value['buyID'] : $ret['id'],
            'sum' => $value['sum'],
            'money' => json_encode([
              'sum' => ['CNY' => $item['CNY'] * $value['sum'], 'point' => $item['point'] * $value['sum']],
              'payment' => ['CNY' => 0, 'point' => 0]
            ]),
            'typeCid' => $item['typeCid'],
            'name' => $value['name'],
            'tel' => $value['tel'],
            'address' => $value['address'],
            'itemInfo' => json_encode($item, JSON_UNESCAPED_UNICODE),
            'other' => $item['other'],
            'tradeNo' => '',
          ];
        }
      }
      $cmd = $tmp;
    } elseif (!strcasecmp($cmd['table'], 'itemType')) { // 商品分类
      $cmd = [
        'table' => 'itemType',
        'createTime' => $t,
        'changeTime' => $t,
        'cuid' => $ret['id'],
        'name' => $cmd['name'],
        'cid' => 0
      ];
    } else {
      return noPrem;
    }
    // $ret = ['result'=>$cmd];
    $ret = ['result' => AddData($cmd)];
    if (!strcasecmp($cmd['table'], 'itemType')) { // 设置cid
      runSql('UPDATE itemtype SET cid=1<<(id-1) WHERE cid=0');
    }
  } else $ret = ['msg' => 'token失效', 'data' => $cmd];
  return $ret;
};


$fun[c['del']] = function ($cmd) {
  $ret = useToken($cmd);
  if ($ret) {
    if ($ret['type'] == 管理员) {
      $ret = ['msg' => '', 'data' => runSql('delete FROM `' . $cmd['table'] . '` WHERE `id`=' . $cmd['id'])];
    } else {
      $ret = ['msg' => '当前token无权限', 'date' => $cmd];
    }
  }
  return $ret;
};

$fun[c['getToken']] = function ($cmd) {
  $ret = getToken($cmd);
  if ($ret) $ret = ['result' => $ret];
  else $ret = ['msg' => 'val参数错误', 'data' => $cmd];
  return $ret;
};
$fun[c['getTokenByWxID']] = function ($cmd) {
  $ret = GetData(['table' => 'users', 'openID' => $cmd['openID']], 'id,username,password,type', true);
  if ($ret) {
    $ret['uniqid'] = uniqid();
    $ret = ['token' => enAes($ret)];
    $ret = ['result' => $ret];
  } else $ret = ['msg' => 'val参数错误,val必须设置属性openID(大小写敏感)', 'data' => $cmd];
  return $ret;
};
$fun[c['getMenu']] = function ($cmd) {
  $user = useToken($cmd);
  $ret = false;
  if ($user) {
    $ret = ['table' => 'itemType', 'cid' => $user['itemTypeCid'] . '&cid'];
    $itemType = GetData($ret, 'id,name,info,cid,img');
    $num = count($itemType);
    $ret = [];
    for ($i = 0; $i < $num; $i++) {
      $ret[] = [
        'label' => $itemType[$i]['name'],
        'key' => 'itemType',
        'val' => $itemType[$i]['id']
      ];
    }
    $ret = [
      ['label' => '用户管理', 'table' => 'users'],
      ['label' => '我的发布', 'table' => 'items', 'children' => $ret],
      ['label' => '交易记录', 'table' => 'transactionLog'],
      ['label' => '评价管理', 'table' => 'itemEval'],
      ['label' => '购物车', 'table' => 'shoppingTrolleys']
    ];
    switch ($user['type']) {
      case 会员:

        break;
      case 商家:

        break;
      case 管理员:
        array_push(
          $ret,
          ['label' => '商品类型', 'table' => 'itemType'],
          ['label' => '车型', 'table' => 'cars'],
          ['label' => '预定须知', 'table' => 'notice'],
          ['label' => '服务承诺', 'table' => 'promise']
        );
        break;

      default:
        $ret = false;
        break;
    }
  } else {
    $ret['cmd'] = $cmd;
    $ret['test'] = time();
    $ret['data'] = deAes($cmd['token']);
  }
  return $ret;
};
$fun[c['getGlobal4']] = function () {
  // cars,itemType,notice,promise
  $ret = [];
  $ret['cars'] = [];
  $ret['itemType'] = GetData(['table' => strtolower('itemType')], 'id,name,info,cid');
  $ret['notice'] = GetData(['table' => 'notice', 'state' => '1'], 'id,name,info,cid');
  $ret['promise'] = GetData(['table' => 'promise', 'state' => '1'], 'id,name,info,cid');
  return $ret;
};
$fun[c['getIndex']] = function () {
  $ret = [];
  $ret['banner'] = json_decode(GetData(['table' => 'items', 'name' => 'banner'], 'imgs', true)['imgs'], true);
  $ret['data'] = GetData(['table' => 'itemType', 'id' => '>2', 'state' => '1'], 'id,name,info,displayNum');
  foreach ($ret['data'] as $key => $value) {
    if ($value['id'] == 11) {
      $tmp = GetData([
        'table' => 'items',
        'flea' => 1,
        'weight' => 1,
        'limit' => '0,' . $value['displayNum']
      ]);
    } else {
      $tmp = GetData([
        'table' => 'items',
        'itemType' => $value['id'],
        'flea' => 0,
        'weight' => 1,
        'limit' => '0,' . $value['displayNum']
      ]);
    }
    foreach ($tmp as $tk => $tv) {
      $tmp[$tk]['cars'] = json_decode($tv['cars'], true);
      $tmp[$tk]['imgs'] = json_decode($tv['imgs'], true);
    }
    $ret['data'][$key]['data'] = $tmp;
  }
  return $ret;
};
